﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections.Specialized;
using System.Web;

namespace Mindfor.Web
{
	/// <summary>
	/// Provides extension functions to Session.
	/// </summary>
	public static class HttpSessionStateExtensions
	{
		/// <summary>
		/// Returns boolean value by key.
		/// </summary>
		/// <param name="session">Session to get value from.</param>
		/// <param name="key">Key.</param>
		/// <returns>Bool value or <c>Null</c> if not found.</returns>
		public static bool? EvalBool(this HttpSessionStateBase session, string key)
		{
			object val = session[key];
			if (val != null)
			{
				if (val is bool)
					return (bool)val;
				else
				{
					bool b = false;
					return bool.TryParse(val.ToString(), out b) ? b : (bool?)null;
				}
			}

			return null;
		}

		/// <summary>
		/// Returns integer value by key.
		/// </summary>
		/// <param name="session">Session to get value from.</param>
		/// <param name="key">Key.</param>
		/// <returns>Integer value or <c>Null</c> if not found.</returns>
		public static int? EvalInt(this HttpSessionStateBase session, string key)
		{
			object val = session[key];
			if (val != null)
			{
				if (val is int)
					return (int)val;
				else
				{
					int i = 0;
					return int.TryParse(val.ToString(), out i) ? i : (int?)null;
				}
			}

			return null;
		}
	}
}
